import { useState } from 'react';
import useEvent from './useEvent';

interface Actions<T> {
  setLeft: () => void;
  setRight: () => void;
  set: (value: T) => void;
  toggle: () => void;
}

function useToggle<T = boolean>(): [boolean, Actions<T>];

function useToggle<T>(defaultValue: T): [T, Actions<T>];

function useToggle<T, U>(defaultValue: T, reverseValue: U): [T | U, Actions<T | U>];

function useToggle<T, U>(defaultValue: T = false as unknown as T, reverseValue?: U) {
  const [state, setState] = useState<T | U>(defaultValue);

  const setLeft = useEvent(() => {
    setState(defaultValue);
  });

  const setRight = useEvent(() => {
    setState((reverseValue === undefined ? !defaultValue : reverseValue) as (T | U));
  });

  const toggle = useEvent(() => {
    defaultValue === state ? setRight() : setLeft();
  });

  return [state, { toggle, set: setState, setLeft, setRight }]
}

export default useToggle;
